﻿using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Http;
using System.Data;
using System;
using System.Web.Script.Serialization;
namespace YZZ
{
    class JSON : JSONStringCreator
    {
        public JSON(DataTable table) : base(table)
        {

        }
        public JSON():base (new DataTable())
        {
            
        }
        
        public HttpResponseMessage ObjectToJson(object obj)
        {
            return JSONResponseCreator.ObjectToJson(obj);
        }
        public static HttpResponseMessage ObjectToJson(List<object> objs)
        {
            return JSONResponseCreator.ObjectToJson(objs);
        }
        public new void AddCol(string columnName, Type type)
        {
            base.AddCol(columnName, type);
        }
        public new DataRow NewRow()
        {
            return base.NewRow();
        }
        public new void AddRow(DataRow row)
        {
            base.AddRow(row);
        }

        #region 解析一个Json对象结构
        /// <summary>
        /// 解析一个Json对象结构
        /// </summary>
        /// <param name="json">Json对象</param>
        /// <returns>Dictionary<string, object>形式的对象内容</returns>
        static public Dictionary<string, object> JsonObjectAnalyze(object json)
        {
            Dictionary<string, object> datajson = (Dictionary<string, object>)json;
            return datajson;
        }
        #endregion

        #region 解析一个Json数组
        /// <summary>
        /// 解析Json数组中的Json对象
        /// </summary>
        /// <param name="json">Json对象</param>
        /// <returns>object[]形式的数组内容</returns>
        static public object[] JsonArrayAnalyze(object json)
        {
            Array jsonArray = (Array)json;
            object[] result = new object[jsonArray.Length];
            for (int i = 0; i < jsonArray.Length; i++)
            {
                object t = jsonArray.GetValue(i);
                result[i] = t;
            }
            return result;
        }
        #endregion

        #region 解析Json数组中的Json对象
        /// <summary>
        /// 解析Json数组中的Json对象
        /// </summary>
        /// <param name="json">Json对象</param>
        /// <returns>Dictionary<string, object>形式的对象内容</returns>
        static public Dictionary<string, object> JsonObjectFromArrayAnalyze(object json)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            IDictionary<string, object> read = (IDictionary<string, object>)json;
            ICollection<string> keys = read.Keys;
            foreach (string key in keys)
            {
                object value;
                read.TryGetValue(key, out value);
                result.Add(key, value);
            }
            return result;
        }
        #endregion
    }

    /// <summary>
    /// 对象转换成JSON格式响应
    /// </summary>
    public class JSONResponseCreator
    {
        /*
        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static IHttpActionResult ObjectToJSON(object obj)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            js.MaxJsonLength = int.MaxValue;
            string r = js.Serialize(obj);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(r, Encoding.UTF8, "text/json")
            };
            return result;
        }
        */
        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static HttpResponseMessage ObjectToJson(object obj)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            js.MaxJsonLength = int.MaxValue;
            string r = js.Serialize(obj);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(r, Encoding.UTF8, "text/json")
            };
            return result;
        }

        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="objs"></param>
        /// <returns></returns>
        public static HttpResponseMessage ObjectToJson(List<object> objs)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            js.MaxJsonLength = int.MaxValue;
            string r = js.Serialize(objs);
            var result = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(r, Encoding.UTF8, "text/json")
            };
            return result;
        }
    }

    /// <summary>
    /// 对象转换JSON格式字符串
    /// </summary>
    class JSONStringCreator : TableTemplate
    {
        private string JSONString;
        //private DataTable m_table;
        public JSONStringCreator(DataTable table): base(table)
        {
            JSONString = "";
            m_table = table;
            if (m_table == new DataTable() || m_table == null)
                return ;
        }
        //  获得由表所转换来的JSON
        public string GetJSONObject()
        {
            if (m_table == new DataTable()) return "";
            if (m_table == null) return "";
            for (int i = 0; i < m_table.Rows.Count; i++)
            {
                //CheckEmptyRow(i);
                WriteJSONObjectLine(i, i + 1 < m_table.Rows.Count);
            }
            GiveBrace();
            return JSONString;
        }
        public string GetJSONArray()
        {
            if (m_table == new DataTable()) return "";
            if (m_table == null) return "";
            for (int i = 0; i < m_table.Rows.Count; i++)
            {
                //CheckEmptyRow(i);
                WriteJSONObjectLine(i, i + 1 < m_table.Rows.Count);
            }
            GiveSBrace();
            JSONString = YZZ.Tools.ReplaceString(JSONString, "\\", "\\\\", false);
            return JSONString;
        }
        public string GetOutputMessage()
        {
            string result = string.Empty;
            string JSONString = GetJSONArray();
            result = "{\"Code\":\"200\",\"Msg\":\"获取成功\",\"TitleData\":null,\"DetailData\":" + JSONString + ",\"Total\":0}";
            return result;
        }

        // 写入一行记录
        private bool WriteJSONObjectLine(int row, bool notLastLine)
        {
            Write("{");
            for (int i = 0; i < m_table.Columns.Count; i++)
            {
                WriteInQuote(m_table.Columns[i].ColumnName);
                Write(":");
                DataRow thisRow = m_table.Rows[row];
                if ((thisRow[m_table.Columns[i].ColumnName].GetType() == System.Type.GetType("System.String")) || (thisRow[m_table.Columns[i].ColumnName].GetType() == System.Type.GetType("System.DateTime")))
                    WriteInQuote(thisRow[m_table.Columns[i].ColumnName].ToString());
                else
                    Write(YZZ.Tools.ShouldHaveNum(thisRow[m_table.Columns[i].ColumnName].ToString(),"0"));
                if (i + 1 < m_table.Columns.Count) Write(",");
            }
            if (notLastLine) Write("},");
            else Write("}");
            return true;
        }
        private bool WriteJSONArrayLine(int row, bool notLastLine)
        {
            Write("[");
            for (int i = 0; i < m_table.Columns.Count; i++)
            {
                DataRow thisRow = m_table.Rows[row];
                if ((thisRow[m_table.Columns[i].ColumnName].GetType() == System.Type.GetType("System.String")) || (thisRow[m_table.Columns[i].ColumnName].GetType() == System.Type.GetType("System.DateTime")))
                    WriteInQuote(thisRow[m_table.Columns[i].ColumnName].ToString());
                else
                    Write(thisRow[m_table.Columns[i].ColumnName].ToString());
                if (i + 1 < m_table.Columns.Count) Write(",");
            }
            if (notLastLine) Write("],");
            else Write("]");
            return true;
        }
        private void Write(string NextString)
        {
            JSONString += NextString;
        }
        private void WriteInSomething(string NextString, string SomethingStart, string SomethingEnd)
        {
            Write(SomethingStart);
            Write(NextString);
            Write(SomethingEnd);
        }
        private void WriteInQuote(string NextString)
        {
            WriteInSomething(NextString, @"""", @"""");
        }
        private void GiveSomething(string Start, string End)
        {
            JSONString = Start + JSONString + End;
        }
        private void GiveBrace()
        {
            GiveSomething("{", "}");
        }
        private void GiveSBrace()
        {
            GiveSomething("[", "]");
        }

        //
        protected new void AddCol(string columnName, Type type)
        {
            base.AddCol(columnName, type);
        }
        protected new DataRow NewRow()
        {
            return base.NewRow();
        }
        protected new void AddRow(DataRow row)
        {
            base.AddRow(row);
        }
    }
}
